package com.youdo.careyes.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;

import com.youdo.careyes.R;

/**
 * 自定义控件
 *
 * @author ljb
 * @date 2025.07.25
 * @email 568838953@qq.com
 * <p>
 */
public class BxSuperSetView extends LinearLayout implements CompoundButton.OnCheckedChangeListener, AdapterView.OnItemSelectedListener, TextWatcher {
    private static final int LayoutStyle_SWITCH = 0;
    private static final int LayoutStyle_SPINNER = 1;
    private static final int LayoutStyle_EDIT = 2;
    private static final int LayoutStyle_ARROW = 3;
    // view
    private SwitchCompat mSwitch;
    private Spinner mSpinner;
    private EditText mInputEt;
    private TextView nameTipTv;
    // 全局变量
    private final Context mContext;
    private TypedArray mTypedArray;
    private int mID = 0;// 用来辨别是哪一个view
    private int mLayoutStyle = 0;// 样式(0-switch,1-spinner,2-edit,3-arrow)
    private String[] mEntryNames;// Spinner对应的显示值
    protected OnSsClick mClickListener;

    // ====================================
    // ===========构造方法-初始化===========
    // ====================================

    /**
     * 在java代码里new的时候会用到
     */
    public BxSuperSetView(Context context) {
        super(context);
        this.mContext = context;
        initView();
    }

    /**
     * 在xml布局文件中使用时自动调用
     */
    public BxSuperSetView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initAttr(attrs);
        initView();
    }

    /**
     * 不会自动调用，如果有默认style时，在第二个构造函数中调用
     */
    public BxSuperSetView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initAttr(attrs);
        initView();
    }

    /**
     * 初始化属性
     */
    @SuppressLint("CustomViewStyleable")
    private void initAttr(AttributeSet attrs) {
        this.mTypedArray = mContext.obtainStyledAttributes(attrs, R.styleable.wd_super_set_view_field);
        mLayoutStyle = mTypedArray.getInt(R.styleable.wd_super_set_view_field_ss_style, 0);
    }

    /**
     * 初始化UI，可根据业务需求设置默认值。
     */
    private void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.widget_super_set_view, this, true);
        mSwitch = findViewById(R.id.widget_super_set_view_sw);
        mSpinner = findViewById(R.id.widget_super_set_view_spinner);
        mInputEt = findViewById(R.id.widget_super_set_view_et);
        nameTipTv = findViewById(R.id.widget_super_set_view_tip_tv);
        if (mTypedArray == null) {
            return;
        }
        TextView mNameTv = findViewById(R.id.widget_super_set_view_name_tv);
        try {
            mID = mTypedArray.getInt(R.styleable.wd_super_set_view_field_ss_id, 0);
            // 选项名
            String temp = mTypedArray.getString(R.styleable.wd_super_set_view_field_ss_name);
            if (!TextUtils.isEmpty(temp)) {
                mNameTv.setText(temp);
            }
            // 提示信息 tip
            temp = mTypedArray.getString(R.styleable.wd_super_set_view_field_ss_name_tip);
            if (!TextUtils.isEmpty(temp)) {
                nameTipTv.setText(temp);
                nameTipTv.setVisibility(View.VISIBLE);
            }
            // 提示信息 hint
            temp = mTypedArray.getString(R.styleable.wd_super_set_view_field_ss_hint);
            if (!TextUtils.isEmpty(temp)) {
                mInputEt.setHint(temp);
            }
            // 编辑框-只能输入整数
            boolean isClassNumber = mTypedArray.getBoolean(R.styleable.wd_super_set_view_field_ss_class_number, false);
            if (isClassNumber) {
                mInputEt.setInputType(InputType.TYPE_CLASS_NUMBER);
            }
            if (mLayoutStyle == LayoutStyle_SPINNER) {
                int arrNameId = mTypedArray.getResourceId(R.styleable.wd_super_set_view_field_ss_spinner_entry_names, 0);
                if (arrNameId > 0) {
                    mEntryNames = getResources().getStringArray(arrNameId);
                }
            }
        } finally {
            mTypedArray.recycle();
        }
        // UI显示
        switch (mLayoutStyle) {
            case LayoutStyle_SPINNER:
                mSpinner.setVisibility(VISIBLE);
                mSpinner.setAdapter(new ArrayAdapter<>(getContext(), R.layout.spinner_drop_down_right_item, mEntryNames));
                break;
            case LayoutStyle_EDIT:
                mInputEt.setVisibility(VISIBLE);
                break;
            case LayoutStyle_ARROW:
                View iv = findViewById(R.id.widget_super_set_view_arrow_iv);
                iv.setVisibility(VISIBLE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mClickListener != null) {
                            mClickListener.onSsLeftClick(mID, BxSuperSetView.this, -1);
                        }
                    }
                });
                break;
            default:
                mSwitch.setVisibility(VISIBLE);
                break;
        }
    }

    // ====================================
    // ==============Switch 方法===========
    // ====================================

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int value = isChecked ? 1 : 0;
        if (mClickListener != null) {
            mClickListener.onSsLeftClick(mID, this, value);
        }
    }

    // ====================================
    // ==============Spinner 方法===========
    // ====================================

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        if (mClickListener != null && position < mEntryNames.length) {
            if (position < mEntryNames.length) {
                mClickListener.onSsLeftClick(mID, this, position);
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        // nop
    }


    // ====================================
    // ===========输入框事件===============-
    // ====================================
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    // ====================================
    // ===========对外开放---接口===========
    // ====================================

    /**
     * 是否选中状态
     */
    public boolean isChecked() {
        return mSwitch.isChecked();
    }

    /**
     * 设置选中状态
     */
    public void setChecked(boolean checked) {
        mSwitch.setOnCheckedChangeListener(null);
        mSwitch.setChecked(checked);
        mSwitch.setOnCheckedChangeListener(this);
    }

    /**
     * 获取列表选项框选中项的值
     */
    public int getSelectedItemPosition() {
        return mSpinner.getSelectedItemPosition();
    }

    /**
     * 设置列表选项框的值
     */
    public BxSuperSetView setSelection(int position) {
        if (position >= mEntryNames.length || position < 0) {
            position = 0;
        }
        mSpinner.setOnItemSelectedListener(null);
        mSpinner.setSelection(position);
        mSpinner.setOnItemSelectedListener(this);
        return this;
    }

    /**
     * 获取编辑框的值
     */
    public String getInputValueStr() {
        return mInputEt.getText().toString().trim();
    }

    /**
     * 获取编辑框的值
     */
    public double getInputValueDouble() {
        String input = mInputEt.getText().toString().trim();
        double setValue = 0;
        try {
            setValue = Float.parseFloat(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return setValue;
    }

    /**
     * 设置编辑框的值
     */
    public void setValueText(String value) {
        //mInputEt.addTextChangedListener(null);
        mInputEt.setText(value);
        //mInputEt.addTextChangedListener(this);
    }

    /**
     * 设置当前值
     */
    public BxSuperSetView setValueInt(int value) {
        if (View.VISIBLE == mInputEt.getVisibility()) { // 开关模式
            setChecked(value > 0);
        } else if (View.VISIBLE == mSpinner.getVisibility()) { // 列表选项框模式
            setSelection(value);
        } else if (View.VISIBLE == mInputEt.getVisibility()) { // 编辑框模式
            setValueText(value + "");
        }
        return this;
    }

    /**
     * 设置当前值
     */
    public BxSuperSetView setTip(String value) {
        nameTipTv.setText(value);
        return this;
    }

    /**
     * 设置监听
     */
    public BxSuperSetView setSsClickListener(OnSsClick listener) {
        this.mClickListener = listener;
        return this;
    }

    // ====================================
    // ===========监听事件---接口===========
    // ====================================
    public interface OnSsClick {
        void onSsLeftClick(int id, BxSuperSetView ss, int spinnerPos);
    }
}